package com.xxl.util;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 全局回复：注册成功的json格式为
 * {
 * "code": 状态码
 * "token": jwt令牌
 * "userInfo":  注册用户的的信息
 * "message":  提示信息
 * "date":登录时间
 * }
 * 全局回复：展示博客json格式为
 * {
 * "code":200 状态码
 * "message":  提示信息
 * "data":数据
 * "date":时间
 * }
 *
 * @author xxl
 * @date 2023/4/1
 */
@Component
public class GlobalResult {

    /**
     * 底层方法，全局同意返回的json格式
     *
     * @param code    状态码
     * @param data    数据
     * @param message 提示信息
     * @param date    时间
     * @param map     自定义键值对
     * @return Map 封装好的json
     */
    private <T> Map<String, Object> result(int code, @Nullable String message, String date, @Nullable T data, @Nullable T... map) {
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("date", date);

        if (code != 0) {
            map1.put("code", code);
        }

        if (data != null) {
            map1.put("data", data);
        }

        if (map != null) {
            assert map.length % 2 == 0 : "数组长度不为偶数";
            for (int i = 0; i < map.length; i += 2) {
                map1.put("" + map[i], map[i + 1]);
            }
        }

        if (message != null) {
            map1.put("message", message);
        }

        return map1;
    }

    private    Map<String, Object> result(int code, String message, String date, Map<String, Object> map) {
        HashMap<String, Object> needMap = new HashMap<>();
        needMap.put("code", code);
        needMap.put("message", message);
        needMap.put("date", date);
        map.entrySet().stream().forEach(k ->{
            needMap.put(k.getKey(),k.getValue());
        });
        return needMap;
    }

    private String getDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return format.format(new Date());
    }

    public Map<String, Object> result(int code, String message) {
        return result(code, message, getDate(), null, null);
    }

    public <T> Map<String, Object> result(int code, String message, T data) {
        return result(code, message, getDate(), data, null);
    }

    public <T> Map<String, Object> result(int code, String message, T data, T... map) {
        return result(code, message, getDate(), data, map);
    }

    public <T> Map<String, Object> result(int code, String message, T... map) {
        return result(code, message, getDate(), null, map);
    }

    public <T> Map<String, Object> result(T... map) {
        return result(0, null, getDate(), null, map);
    }

    public <T> Map<String, Object> resultMap(int code, String message, Map<String, Object> map) {
        return result(code, message, getDate(), map);
    }
}
